package gameLogic

import (
	"net"
	"google.golang.org/protobuf/proto"
	// "server_cluster/chat/db"
	//"server_cluster/common/myepoll"
	// "server_cluster/common/tools"
	"server_cluster/chat/sharemem"
	"server_cluster/common/config"
	"server_cluster/common/logger"
	"server_cluster/common/mysock"
	"server_cluster/common/protoc/pb"
)

func ShmUserCheck() {
	//	return
	var kill_time int64
	var myshm = sharemem.Myshm
	user_map := sharemem.GetShmUserMap()
	for _, v := range user_map {
		kill_time = v.GetKillTime()
		if kill_time > 0 && myshm.Time_now > kill_time{
			v.Clean_user()
		}
	}
}

func BattleCreate(conn net.Conn, mybuf *mysock.SockBuf, fd int32) {
	// 获取LOGIC数据
	createreq := pb.SS_Create_Battle{}
	err := proto.Unmarshal(mybuf.Data[mysock.HEAD_LEN:mysock.HEAD_LEN+mybuf.Data_length], &createreq)
	if err != nil {
		logger.Error("parse Fight create error:%v", err)
		mybuf.Code = config.PROTO
		mybuf.WriteTo(conn, nil)
		return
	}
	uid := int64(mybuf.Session)
	// logger.Info("uid=%d token=%s,err=%v",uid,token,nerr)
	// logger.Info("fight_data = %v",fight_data)
	// 本机查询缓存是否还在
	shm_user := sharemem.GetShmUserByUid(uid)
	if shm_user != nil {
		// 缓存还在
		/*
		shm_fd := shm_user.GetFd()
		// 先断开老连接old_fd
		if shm_fd > 0 && fd != shm_fd {
			conns := myepoll.Eps.GetConnByFd(shm_fd)
			if conns != nil {
				conns.Socket.Close()
				myepoll.Eps.Fds.Delete(shm_fd)
			}
		}*/
		shm_user.SetFd(fd)
		// 直接使用
//		logger.Info("get data from sharemem")
	} else {
		// new共享内存user
		shm_user = sharemem.Get_user_by_id(uid, fd)
	}
	if shm_user == nil {
		mybuf.Code = config.FULL
		mybuf.WriteTo(conn, nil)
		return
	}
	//logger.Info("create fight index = %d", shm_user.GetIndex())
	// 创建战斗
	(*shm_user).DeleteShmUserAllMap()
	// 返回消息
}
